<?php
/**
 * Created by PhpStorm.
 * User: apple
 * Date: 2020/10/20
 * Time: 10:27 AM
 */
namespace app\service;
require root_path().'vendor/qiniu/php-sdk/autoload.php';

use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use think\facade\Config;

class QiniuService
{
    private static $bucket;
    private static $accessKey;
    private static $secretKey;
    private static $policyConfig;
    private static $domain;

    public function __construct()
    {
        $config = Config::get('uploader.qiniu');
        self::$policyConfig = $config['policy'];
        self::$accessKey = $config['accessKey'];
        self::$secretKey = $config['secretKey'];
        self::$bucket = $config['public']['bucket'];
        self::$domain = $config['public']['domain'];

    }

    public function getToken($type = 'all')
    {

        // 验证
        if (!isset(self::$policyConfig[$type])) {
            fail('请设置上传类型type[eg: '.implode(',', array_keys(self::$policyConfig)).']');
        }

        $auth = new Auth(self::$accessKey, self::$secretKey);

        //获取token
        return $auth->uploadToken(self::$bucket);

    }

    public static function getFullPath($key){
        trace(self::$domain);
        return self::$domain.$key;
    }

    public function getDomain(){
        return self::$domain;
    }
    /**
     * 上传文件
     * @param $file
     * @return array
     * @throws \Exception
     */
    public function upload($file) {

        // 要上传文件的本地路径
        $filePath = root_path() . config()['uploader']['local']['root_path'] . "/" . $file['path'];
        $key = $file['fileName'];
        // 初始化 UploadManager 对象并进行文件的上传
        $uploadMgr = new UploadManager();

        $token = $this->getToken();
        // 调用 UploadManager 的 putFile 方法进行文件的上传
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);

        if ($err === null) {
            $path = $this->getFullPath($ret['key']);
            return ['path' => $path, 'key' => $ret['key']];
        } else {
            return $err;
        }
    }

    public function getInfo($key){

        $auth = new Auth(self::$accessKey, self::$secretKey);
        $bucketMgr = new BucketManager($auth);
        list($fileInfo, $err) = $bucketMgr->stat(self::$bucket,$key);
        if($err){
            fail($err);
        }
        success($fileInfo);

    }

    public function put($data){
        $token = $this->getToken();
        $uploadMgr = new UploadManager();
        return $uploadMgr->put($token,'images/'.time().mt_rand(1,10000),$data);
    }
}